package ktvutil

import (
	"bitbucket.org/kardianos/service"
	"fmt"
	//"log"
	"os"
)

// 启动服务
func StartMainFunc(serviceName string, serviceDesc string, doWork func(), stopWork func()) {

	// 防止NT服务描述为空
	if serviceDesc == "" {
		serviceDesc = serviceName
	}

	var s, err = service.NewService(serviceName, serviceName, serviceDesc)
	//log = s

	if err != nil {
		fmt.Printf("%s unable to start: %s", serviceName, err)
		return
	}

	//var err error

	if len(os.Args) > 1 {

		verb := os.Args[1]
		switch verb {
		// 安装服务
		case "-i", "/i":
			err = s.Install()
			if err != nil {
				fmt.Printf("Failed to install: %s\n", err)
				return
			}
			fmt.Printf("Service \"%s\" installed.\n", serviceName)
		// 卸载服务
		case "-u", "/u":
			err = s.Remove()
			if err != nil {
				fmt.Printf("Failed to remove: %s\n", err)
				return
			}
			fmt.Printf("Service \"%s\" removed.\n", serviceName)
		// 从NT服务自动
		case "-s":
			err = s.Run(func() error {
				// start
				go doWork()
				return nil
			}, func() error {
				// stop
				stopWork()
				return nil
			})
		case "-start", "/start":
			err = s.Start()
			if err != nil {
				fmt.Printf("Failed to start: %s\n", err)
				return
			}
			fmt.Printf("Service \"%s\" started.\n", serviceName)
		case "-stop", "/stop":
			err = s.Stop()
			if err != nil {
				fmt.Printf("Failed to stop: %s\n", err)
				return
			}
			fmt.Printf("Service \"%s\" stopped.\n", serviceName)
		}
		return
	} else {
		// 没有添加参数, 直接启动函数
		doWork()
	}

	if err != nil {
		s.Error(err.Error())
	}
}
